package com.xxpt.common.utils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Map工具类
 * @Author masl - 2018/10/12 10:48
 */
public class MapUtils extends HashMap<String, Object> {

    @Override
    public MapUtils put(String key, Object value) {
        if (value instanceof String) {
            value = org.apache.commons.lang.StringUtils.trim(value + "");
        }
        super.put(key, value);
        return this;
    }

    public static Integer getInteger(Map<String, Object> map, String key) {
        if (!map.containsKey(key))
            return null;
        return map.get(key) == null ? null : Integer.valueOf(map.get(key).toString());
    }

    public static String getString(Map<String, Object> map, String key) {
        if (!map.containsKey(key))
            return null;
        return map.get(key) == null ? null : map.get(key).toString();
    }

    public static Double getDouble(Map<String, Object> map, String key) {
        if (!map.containsKey(key))
            return null;
        return map.get(key) == null ? null : Double.valueOf(map.get(key).toString());
    }

    public static BigDecimal getBigDecimal(Map<String, Object> map, String key) {
        if (!map.containsKey(key))
            return null;
        return map.get(key) == null ? null : new BigDecimal(map.get(key).toString());
    }

    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            return null;
        }
    }
}
